package com.macoli.mock_server.httpserver

import com.macoli.mock_server.MockService
import com.macoli.mock_server.common.Configuration
import com.macoli.mock_server.httpserver.route.Router
import com.macoli.mock_server.utils.FileUtils
import com.macoli.mock_server.utils.LogUtils
import fi.iki.elonen.NanoHTTPD
import java.io.FileInputStream
import javax.inject.Inject


class HttpServer(hostname : String?, port : Int) : NanoHTTPD(hostname , port) {
    @Inject
    lateinit var router : Router
    @Inject
    lateinit var configuration: Configuration
    init {
        MockService.getMockService().getBaseComponent().injectHttpServer(this)
    }
    override fun serve(session: IHTTPSession?): Response {
        return dealWith(session)
    }

    private fun dealWith(session: IHTTPSession?): Response {
        //日志输出外部请求相关的日志信息
       LogUtils.d("dealWith: session.uri = ${session?.uri}, method = ${session?.method}, header = ${session?.headers}, " +
                    "params = ${session?.parameters}"
        )
        if (session == null) {
            return newFixedLengthResponse("500 http server error, session is null")
        }
        if (Method.GET == session.method) {
            router.route(session.uri , session.parameters)?.apply {
                if (!this.static) {
                    val path = configuration.basePath + "/get/" + this.destnation
                    val responseData = FileUtils.readFile(path)
                    return newFixedLengthResponse(responseData)
                } else {
                    val fileInputStream = FileInputStream(configuration.basePath + "/static/" + this.destnation)

                    return newFixedLengthResponse(Response.Status.OK,"application/octet-stream",
                        fileInputStream,fileInputStream.available().toLong())
                }
            }

        } else if (Method.POST == session.method) {//响应post请求
            val files: Map<String, String> = HashMap()
            val params = HashMap<String , List<String>>()
            session.parseBody(files)
            val postData = files["postData"]
            if (postData != null) {
                params["postData"] = mutableListOf(postData)
            }
            val destnation = router.route(session.uri , session.parameters)
            if (destnation != null) {
                val path = configuration.basePath + "/post/" + destnation.destnation
                val responseData = FileUtils.readFile(path)
                return newFixedLengthResponse(responseData)
            }
        }
        return newFixedLengthResponse(Response.Status.NOT_FOUND , NanoHTTPD.MIME_HTML, "404")
    }


}